package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/5/23 16:46
 * Version:1.0-SNAPSHOT
 * Description:
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/showUpload")
    public String showUpload(){
        return "upload";
    }

    // 由于文件对象是一个CommonsMultipartFile
    // 这是一个对象类型
    // 因此,@RequestParam注解不能省略
    @RequestMapping("/upload")
    public void upload(String username, @RequestParam(value = "file",required = false) CommonsMultipartFile file, HttpSession session){
        System.out.println("username:"+username);
        String path = session.getServletContext().getRealPath("/upload");
        File f = new File(path);
        f.mkdirs();
        if(!file.isEmpty()){
            try {
                file.transferTo(new File(path,file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @RequestMapping("/uploads")
    public void uploads(String username, @RequestParam(value = "file",required = false) CommonsMultipartFile[] files, HttpSession session){
        System.out.println("username:"+username);
        String path = session.getServletContext().getRealPath("/upload");
        File f = new File(path);
        f.mkdirs();
        for(CommonsMultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    file.transferTo(new File(path, file.getOriginalFilename()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @RequestMapping("/showDownload")
    public String showDownload(){
        return "download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        // 文件
        String path = session.getServletContext().getRealPath("/js/jquery-3.4.1.min.js");
        File file = new File(path);

        // 响应头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment","jquery-3.4.1.min.js");

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

}
